from django.conf.urls import url, include
from django.shortcuts import HttpResponse
from .app_conf import API_view, DeleteView
import json

def format_json(data={}, code=2000, msg = "success"):
    return json.dumps({
            "code":code,
            "msg": msg,
            "data": data
    })



class ModelXadmin(object):
    list_display = ["id", "__str__"]
    modelform_class = None

    def __init__(self, model, site):
        self.model = model
        self.site = site

    def list_view(self, request):
        # print("self.model", self.model)  # 用户访问哪张表，self.model就是谁。
        model_name = self.model._meta.verbose_name
        data_list = self.model.objects.all()
        # print("list_display:", self.list_display)  ## ['title', 'prcie']

        # 处理表头
        # header_list=["ID","书籍名称","出版社"]
        header_list = []
        list_display = self.list_display
        if "id" not in list_display:
            init_list = ["id"]
            init_list.extend(list_display)
            list_display = init_list

        for field in list_display:  # [check,"nid","title","publish",edit,delete]
            if isinstance(field, str):
                if field == "__str__":
                    val = self.model._meta.model_name.upper()
                    header_list.append({"field": "__str__", "title": val, "type": "str"})
                else:
                    field_obj = self.model._meta.get_field(field)

                    val = field_obj.verbose_name
                    # ---------------------------判断数据类型
                    types = field_obj.description._proxy____args[0].split("(")[0].strip()

                    header_list.append({"field": field, "title": val, "type": types})
            else:
                val = field(self, is_header=True)  # 获取表头，传is_header=True
                if isinstance(val, bool):
                    header_list.append({"field": field.__name__, "title": val, "type": "Boolean"})
                else:
                    header_list.append({"field": field.__name__, "title": val, "type": "str"})

        # 处理表单数据
        new_data_list = []
        for obj in data_list:  # data_list [book_obj,book_obj2,...]
            temp = {}
            for field in list_display:  # ['title', 'prcie',edit,delete]
                if isinstance(field, str):
                    if field == "__str__":
                        val = obj.__str__()
                    else:
                        val = getattr(obj, field)

                    import datetime
                    date = datetime.datetime.now()

                    if type(val) == type(date):
                        val = val.strftime("%Y-%m-%d %H:%M:%S")
                    if isinstance(val, object):
                        val = val.__str__()
                else:
                    val = field(self, obj)
                    field = field.__name__
                temp[field] = val

            new_data_list.append(temp)

        # print("头", header_list)
        # print("数据", new_data_list)
        """
        头：
        [
        {"field":"name", "title": "姓名"}
        ]
        
        身体:
        [
        {"title":"标题", "name":"名字"},
        {"title":"标题1", "name":"名字1"}
        ]
        """

        ret = {"code": 2000, "model_name": model_name, "header_list": header_list, "data_list": new_data_list}
        return HttpResponse(format_json(ret, code=2000), content_type="application/json")

    def get_modelform_class(self):
        """
        系统自带的modelForm方式。
        :return:
        """
        if not self.modelform_class:
            from django.forms import ModelForm
            from django.forms import widgets as wid
            class ModelFormDemo(ModelForm):
                class Meta:
                    model = self.model
                    fields = "__all__"
            return ModelFormDemo
        else:
            return self.modelform_class

    def _building_form_dict(self, form):
        """
        传递form数据，构建需要的数据
        :param form:
        :return:
        """
        form_data = []
        for item in form:
            # 判断错误信息
            if len(item.errors) == 0:
                error = ""
            else:
                error = str(item.errors[0])

            if 'type="text"' in str(item):
                form_data.append({"type": "input", "label": item.label, "name": item.name, "value": item.value(), "error": error})

            if "select" in str(item):
                option_list = []
                key = True
                for option in item:
                    # 过滤掉第一个
                    if key:
                        key = False
                    else:
                        option_list.append({"label": option.data['label'], "value": option.data['value']})

                form_data.append({"type": "select", "label": item.label, "name": item.name, "value": item.value(), "error": error, "option": option_list})

            if 'type="checkbox"' in str(item):
                form_data.append({"type": "checkbox", "label": item.label, "name": item.name, "value": item.value(), "error": error })

        """
        [
        {"type": "input", "label": "毛毛", "name":"maomao", "value": "", "error":""},
        {"type": "select", "label": "多选", "name": "select", "value": "",  "error":"", "option":[{"label":"区域一", "value":"shanghai"},{"label":"区域二", "value":"beijing"}]}
        ]
        """
        return form_data


    def add_view(self, request):
        # 获取modelform类  可能是系统自定义的  也可以能是用户写的
        ModelFormDemo = self.get_modelform_class()

        form = ModelFormDemo()

        if request.method == "POST":
            # print("====",request.POST)
            print("====",request.POST)

            form = ModelFormDemo(request.POST, request.FILES)
            if form.is_valid():
                form.save()
                ret = {"code": 2000, "msg":"提交成功"}
                return HttpResponse(format_json(ret, code=2000), content_type="application/json")

            form_data = self._building_form_dict(form)
            ret = {"code": 4000, "form_data": form_data}
            return HttpResponse(format_json(ret, code=4000), content_type="application/json")

        # print("========",str(form))
        form_data = self._building_form_dict(form)
        ret = {"code":2000, "form_data": form_data}
        return HttpResponse(format_json(ret, code=2000), content_type="application/json")

    def change_view(self, request, id):
        ModelFormDemo = self.get_modelform_class()
        edit_obj = self.model.objects.filter(pk=id).first()

        if request.method == "POST":
            # print("====",request.POST)
            print("====",request.POST)

            form = ModelFormDemo(request.POST, instance=edit_obj)
            if form.is_valid():
                form.save()
                ret = {"code": 2000, "msg":"提交成功"}
                return HttpResponse(format_json(ret, code=2000), content_type="application/json")

            form_data = self._building_form_dict(form)
            ret = {"code": 4000, "form_data": form_data}
            return HttpResponse(format_json(ret, code=4000), content_type="application/json")


        form = ModelFormDemo(instance=edit_obj)

        form_data = self._building_form_dict(form)
        ret = {"code": 2000, "form_data": form_data}
        return HttpResponse(format_json(ret, code=2000), content_type="application/json")

    def delete_view(self, request, id):
        if request.method == "POST":
            print(123)
            self.model.objects.filter(pk=id).delete()

        return HttpResponse("delete_view")

    def get_urls_2(self):
        temp = []

        temp.append(url(r"^$", self.list_view))
        temp.append(url(r"^add/$", self.add_view))
        temp.append(url(r"^(\d+)/change/$", self.change_view))
        temp.append(url(r"^(\d+)/delete/$", DeleteView.as_view()))

        return temp

    @property
    def urls2(self):
        return self.get_urls_2(), None, None


class XadminSite(object):
    def __init__(self, name='admin'):
        self._registry = {}
        self.name = name

    def get_urls(self):
        temp = []

        temp.append(url(r'^get_app_conf',API_view.as_view()))
        for model, admin_class_obj in self._registry.items():

            app_name = model._meta.app_label       # app名字
            model_name = model._meta.model_name   # 模型名字
            temp.append(url(r'^{0}/{1}/'.format(app_name, model_name), admin_class_obj.urls2), )

        return temp


    @property
    def urls(self):
        return self.get_urls(), None, None

    def register(self, model, admin_class=None, **options):
        if not admin_class:
            admin_class = ModelXadmin
        self._registry[model] = admin_class(model, self)


site = XadminSite()